using System;
using MSScriptControl;
using InfoJetSoft.Service.ManagedCode;
using InfoJetSoft.Service.Entity;

namespace InfoJetSoft.Service.Util
{
	/// <summary>
	/// Summary description for ScriptControlContext.
	/// </summary>
	public class ScriptControlContext
	{
		//CID 0346 //2009.10.22 //Begin
		private ScriptControlClass scriptControl = null;
		//CID 0346 //2009.10.22 //End
		private XDocument xdoc = null;
		private Application app = null;

		public static void buildContext( ScriptSource scriptSource, Form form )
		{
			ScriptControlClass scriptControl = new ScriptControlClass();

			XDocument xdocument = new XDocument( form );
			Application application = new Application( form );

			scriptControl.AllowUI = false;
			scriptControl.Language = scriptSource.Language;
            //CID 0652 //2010.09.08 //Begin
            if (ConfigUtil.UseSafeSubset())
            {
                scriptControl.UseSafeSubset = true;
            }
            //CID 0652 //2010.09.08 //End
			//Const NoTimeout = -1 (HFFFFFFFF). 
			//Setting ScriptControl.Timeout to this value prevents timeout check from occurring
			scriptControl.Timeout = -1;
			
			scriptControl.AddObject( "XDocument", xdocument, false );
			scriptControl.AddObject( "Application", application, false );

			foreach( string src in scriptSource.ScriptList )
			{
				scriptControl.AddCode( src );
			}

			ScriptControlContext context = new ScriptControlContext();
			context.ScriptControl = scriptControl;
			context.XDocument = xdocument;
			context.Application = application;

			form.ScriptControlContext = context;
		}

		public static void updateContext(Form form)
		{
			if( form.ScriptControlContext != null )
			{
				XDocument xdoc = form.ScriptControlContext.XDocument;
				xdoc.DOM = new XMLDocument( form, form.XmlDoc, form.XmlNsResolver );
			}
		}

		public ScriptControlClass ScriptControl
		{
			get
			{
				return scriptControl;
			}
			
			set
			{
				this.scriptControl = value;
			}
			
		}

		public XDocument XDocument
		{
			get
			{
				return xdoc;
			}
			
			set
			{
				this.xdoc = value;
			}
			
		}

		public Application Application
		{
			get
			{
				return app;
			}
			
			set
			{
				this.app = value;
			}
			
		}

		//CID 0371 //2009.07.17 //Begin
		public static void Release( Form form )
		{
			if( form.ScriptControlContext != null )
			{
				System.Runtime.InteropServices.Marshal.ReleaseComObject( form.ScriptControlContext.ScriptControl );
			}
		}
		//CID 0371 //2009.07.17 //End

	}
}
